#!/bin/bash

set -o nounset
#set -o errexit
#set -o xtrace

RED='\033[0;31m'
GREEN='\033[32;1m'
YELLOW='\033[33;1m'
NC='\033[0m' # No Color

# default version, can be overridden by cmd line options
REGISTRY_MIRROR=${REGISTRY_MIRROR:-"CN"}
DOCKER_VERSION=${DOCKER_VERSION:-"24.0.7"}

if [ $(arch) == "x86_64" ] || [ $(arch) == "amd64" ]; then
    DOCKER_VER=${DOCKER_VERSION}
elif [ $(arch) == "aarch64" ] || [ $(arch) == "arm64" ]; then
    DOCKER_VER=arm-${DOCKER_VERSION}
fi
DOCKER_URL="https://pkg.rainbond.com/offline/docker/docker-${DOCKER_VER}.tgz"

function install_docker() {
    # check if a container runtime is already installed
    systemctl status docker | grep Active | grep -q running && {
        docker_version=$(sudo docker version | grep -A 10 Server | grep Version | awk '{print $2}')
        docker_ver_major=$(echo "$docker_version" | awk -F "." '{print $1}')
        docker_ver_minor=$(echo "$docker_version" | awk -F "." '{print $2}')
        if [ "$docker_ver_major" == "1" ]; then
            if [ "$docker_ver_minor" == "12" ]; then
                echo -e "${RED}[ERROR] If your host has Dokcer installed, please make sure that the version cannot be less than 1.13.x ${NC}"
                exit 1
            fi
        else
            echo -e "${YELLOW}[WARN] Docker has been installed on the host ${NC}"
            exit 1
        fi
    }

    sudo mkdir -p /usr/local/bin /etc/docker /opt/docker/down
    if [[ -f "/opt/docker/down/docker-${DOCKER_VER}.tgz" ]]; then
        echo -e "${GREEN}[INFO] docker binaries already existed ${NC}"
    else
        echo -e "${GREEN}[INFO] downloading docker binaries ${DOCKER_VER} ${NC}"
        if [[ -e /usr/bin/curl ]]; then
            curl -C- -O --retry 3 "${DOCKER_URL}" || {
                echo -e "${RED}[ERROR] downloading docker failed ${NC}"
                exit 1
            }
        else
            wget -c "$DOCKER_URL" || {
                echo -e "${RED}[ERROR] downloading docker failed ${NC}"
                exit 1
            }
        fi
        sudo mv ./docker-${DOCKER_VER}.tgz /opt/docker/down
    fi

    sudo bash -c 'tar zxf /opt/docker/down/docker-*.tgz -C /opt/docker/down &&
        mv /opt/docker/down/docker/* /usr/local/bin &&
        ln -sf /usr/local/bin/docker /bin/docker && rm -rf /opt/docker/down'

    echo -e "${GREEN}[INFO] generate docker service file ${NC}"
    sudo bash -c 'cat >/etc/systemd/system/docker.service <<EOF
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.io
[Service]
OOMScoreAdjust=-1000
Environment="PATH=/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin"
ExecStart=/usr/local/bin/dockerd
ExecStartPost=/sbin/iptables -I FORWARD -s 0.0.0.0/0 -j ACCEPT
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Delegate=yes
KillMode=process
[Install]
WantedBy=multi-user.target
EOF'

    # configuration for dockerd
    echo -e "${GREEN}[INFO] generate docker config file ${NC}"
    if [[ "$REGISTRY_MIRROR" == CN ]]; then
        echo -e "${GREEN}[INFO] prepare register mirror for ${REGISTRY_MIRROR} ${NC}"
        sudo bash -c 'cat >/etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://dockerhub.azk8s.cn",
    "https://docker.mirrors.ustc.edu.cn",
    "http://hub-mirror.c.163.com"
  ],
  "max-concurrent-downloads": 10,
  "max-concurrent-uploads": 10,
  "log-driver": "json-file",
  "log-level": "warn",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
    },
  "data-root": "/var/lib/docker"
}
EOF'
    else
        echo -e "${GREEN}[INFO] standard config without registry mirrors ${NC}"
        sudo 'cat >/etc/docker/daemon.json <<EOF
{
  "max-concurrent-downloads": 10,
  "log-driver": "json-file",
  "log-level": "warn",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
    },
  "data-root": "/var/lib/docker"
}
EOF'
    fi

    if [[ -e /etc/centos-release || -e /etc/redhat-release ]]; then
        echo -e "${GREEN}[INFO] turn off selinux in CentOS/Redhat ${NC}"
        sudo setenforce 0
        sudo sed -ir "s/^SELINUX=.*/SELINUX=disabled/" /etc/selinux/config
    fi

    echo -e "${GREEN}[INFO] Enable and start docker ${NC}"
    sudo systemctl enable docker
    sudo systemctl daemon-reload && sudo systemctl restart docker && sleep 8 && echo -e "${GREEN}[INFO] Docker installed successfully ${NC}"
}

function check_iptables() {
    os_type=$(cat /etc/os-release | grep "^ID=" | awk -F= '{print $2}' | tr -d [:punct:])
    os_version_id=$(cat /etc/os-release | grep "VERSION_ID=" | awk -F= '{print $2}' | tr -d [:punct:])

    if [[ -e /usr/sbin/iptables ]] || [[ -e /sbin/iptables ]]; then
        echo -e "${GREEN}[INFO] iptables already installed ${NC}"
    else
        case $os_type in
        debian)
            if [[ "$os_version_id" == "11" ]]; then
                echo -e "${RED}[ERROR] iptables not installed, Please install iptables manually 'apt-get update && apt install -y iptables-persistent', Execute the script again after the installation is complete.${NC}"
                exit 1
            fi
        ;;
        *)
            echo -e "${RED}[ERROR] Installation of iptables via script is not supported, Please install iptables manually ${NC}"
            exit 1
        ;;
        esac
    fi
}

# check iptables
check_iptables

# install docker
install_docker
